<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
		<style>
			* {
				margin: 0;
				padding: 0;
				text-decoration: none;
			}
			#hd {
				width: 100%;
				height: 200px;
				background: lightblue;
			}			
			nav {
				width: 100%;
				height: 50px;
				background: deeppink;
			}			
			a {
				position: fixed;
				right: 15px;
				bottom: 15px;
			}
		</style>
		<script type="text/javascript">
			window.onload = function() {
				var oA = document.querySelector('a')
				var speed = 0;
				var timer = null;
				var bstop = true;

				oA.onclick = function() {
					timer = setInterval(function() {
						var scroll = document.documentElement.scrollTop || document.body.scrollTop;
						speed = scroll / 10;
						document.documentElement.scrollTop = document.body.scrollTop = scroll - speed;
						if(scroll <= 0) {
							clearInterval(timer);
						}
						bstop = true;//这里重新让定时器一直执行  知道不满足
					}, 50)
				}

				var oNav = document.querySelector('nav');
				var oHd = document.getElementById('hd');
				window.onscroll = function() {
					var scroll = document.documentElement.scrollTop || document.body.scrollTop;
					if(scroll > 200) {
						oNav.style.position = 'fixed';
						oNav.style.top = 0;
					} else {
						oNav.style.position = 'static';
					}
					if(!bstop) {//上面的代码50毫秒触发一次，50毫秒上面代码触发一次onscroll事件。
						clearInterval(timer);//onscroll连续触发2次以上，才能让让bstop=false起作用  
					}
					bstop = false;
				}
			}
		</script>
	</head>

	<body style="height: 4000px;">
		<div id="hd"></div>
		<nav></nav>
		<a href="javascript:;">回到顶部</a>
	</body>

</html>